<?php

namespace app\admin\model;

use think\Model;
use think\Db;

class Container extends Model
{
    
    function getContainersContent($where,$type,$lang,$port_id=0)
    {
        // 获取准备状态货柜
        $container = getDatas('container',['id,name,ready_day,sum_ctn,sum_kgs,sum_cbm,sum_value,create_id,create_at'],['ready_day'=>['>',0]],'ready_day asc');
        if(!empty($container)){
            foreach ($container as $k => $v) {
                $container[$k]['create_name'] = getinfo($v['create_id'], 'admin')['nickname'];//编辑者
                $container[$k]['create_name'] = getTimeDates($v['create_at'],9,$lang);
            }

            if($type == 'add'){
                // 获取装箱清单
                $buy_po = model('Buy')->getBuyPo($where,$lang, ['zu.id,zu.company_id,zu.delivery_day,zu.paid_sum,zu.price_sum,zu.cost_sum']);
                $where['container_id'] = 0;
            }else{
                // 如果不传 则获取第一个货柜的装箱清单数据
                if(empty($where)){
                    $where['container_id'] = $container[0]['id'];
                }
                // 获取合同Id
                $po_ids = getGroup('buy_po_pack',['po_id'],$where,'po_id');
                if(!empty($po_ids)){
                    $res = array_column($po_ids, 'po_id');
                    $po_ids = implode($res, ',');
                }
                // dump($po_ids);die;
                $wherepo_id = ['zu.id'=>['in',$po_ids]];
                $buy_po = model('Buy')->getBuyPo($wherepo_id,$lang, ['zu.id,zu.company_id,zu.delivery_day,zu.paid_sum,zu.price_sum,zu.cost_sum']);
            }
            
            $buy_po_pack = [];
            $footer = [];
            if(!empty($buy_po)){
                $where2['container_id'] = $where['container_id'];
                if($port_id){
                    $where2['port_id'] = $port_id;
                }
                $buy_po_pack = model('Buy')->getPoPack($buy_po,$where2,$lang);
                if(!empty($buy_po_pack)){
                    $footer['num'] = count($buy_po_pack);
                    $footer['sum_CTN'] = 0;
                    $footer['sum_KGS'] = 0;
                    $footer['sum_CBM'] = 0;
                    $footer['sum_CNY'] = 0;
                    foreach ($buy_po_pack as $k1 => $v1) {
                        $footer['sum_CNY'] += $v1['CNY'];
                        $footer['sum_CTN'] += $v1['CTN'];
                        $footer['sum_KGS'] += $v1['KGS'];
                        $footer['sum_CBM'] += $v1['CBM'];
                    }
                }
            }
            $returnData['container'] = $container;
            $returnData['buy_po_pack']['content'] = $buy_po_pack;
            $returnData['buy_po_pack']['footer'] = $footer;
            // dump($returnData);die;
        }else{
            $returnData = [];
        }
        return $returnData;
    }   

    //货柜列表
    public function getcontainer($res)
    {
        $map=array();
        if (isset($res['status']) && $res['status']==1){
            //准备
            $map['ready_day']= array('gt',0);
            $map['sum_ctn']= array('eq',0);
            $map['etd_day']= null;
            $map['eta_day']= null;
            $map['arrival_day']= null;
        }elseif (isset($res['status'])&& $res['status']==2){
            //装柜
            $map['ready_day']= array('gt',0);
            $map['sum_ctn']= array('gt',0);
            $map['etd_day']= null;
            $map['eta_day']= null;
            $map['arrival_day']= null;
        }elseif (isset($res['status'])&& $res['status']==3){
            //出发
            $map['etd_day']= array('gt',0);
            $map['eta_day']= null;
            $map['arrival_day']=null;
        }elseif (isset($res['status'])&& $res['status']==4){
            //到达
            $map['eta_day']= array('gt',0);
            $map['arrival_day']= null;
        }elseif (isset($res['status'])&& $res['status']==5){
            //完成
            $map['arrival_day']= array('gt',0);
        }
        $data=Db::name('container')->where($map)->page($res['page'],$res['pageSize'])->select();
        $lang=$res['lang'];
        foreach ($data as $datakey=>$dataval){
            $data[$datakey]['port_start_name']=getinfo($dataval['port_start'],'port')['name'];//出发地
            $data[$datakey]['port_arrival_name']=getinfo($dataval['port_arrival'],'port')['name'];//目的地
            if ($dataval['arrival_day']>0){
                //完成
                $data[$datakey]['status']='DISCHARGE';
            }elseif ($dataval['eta_day']>0 && !$dataval['arrival_day']){
                //到达
                $data[$datakey]['status']='ARRIVE';
            }elseif ($dataval['etd_day']>0 && !$dataval['eta_day'] && !$dataval['arrival_day']){
                //出发
                $data[$datakey]['status']='SALLING';
            }elseif ($dataval['ready_day']>0 && $dataval['sum_ctn']>0 && !$dataval['etd_day'] && !$dataval['eta_day'] && !$dataval['arrival_day']){
                //装柜
                $data[$datakey]['status']='LOADING';
            }elseif ($dataval['ready_day']>0 && $dataval['sum_ctn']==0 && !$dataval['etd_day'] && !$dataval['eta_day'] && !$dataval['arrival_day']){
                //准备
                $data[$datakey]['status']='READY';
            }
            //状态中的时间
            if($lang!='zh'){
                if($dataval['arrival_day']){
                    $data[$datakey]['status_time']=getTimeDate($dataval['arrival_day'],8);
                }
            }else{
                if($dataval['arrival_day']){
                    $data[$datakey]['status_time']=getTimeDate($dataval['arrival_day'],7);
                }
            }
            //承运商名称
            $containerwhere['mkey'] = 'container_carrier_' . $dataval['carrier_id'];
            $data[$datakey]['carriername'] = getlangname('multi_lang', $containerwhere, $lang);
            //编辑者编辑时间
            $data[$datakey]['mangname'] = getinfo($dataval['update_id'], 'admin')['nickname'];//编辑者
            $data[$datakey]['update_date'] = getTimeDate($dataval['update_at'],12);

            //货柜类型名称
            $data[$datakey]['container_type_name']=getinfo($dataval['type_id'],'container_type')['name'];

            //出发货贷
            $data[$datakey]['co_id_start_name']=getinfo($dataval['co_id_start'],'container_agent')['name'];
            //到达贷贷
            $data[$datakey]['co_id_arrival_name']=getinfo($dataval['co_id_arrival'],'container_agent')['name'];
            //处理货柜的准备时间
            if ($lang != 'zh') {
                //发生日期
                $data[$datakey]['ready_date'] = getTimeDate($dataval['ready_day'], 11);
            } else {
                $data[$datakey]['ready_date']  = getTimeDate($dataval['ready_day'], 10);
            }
        }
        $datares['data']=$data;
        $datares['size']=Db::name('container')->where($map)->count();
        $datares['ids'] = array_column($data, 'id');//货柜id
        $datares['ready_date'] = array_values(array_unique(array_column($data, 'ready_date')));//准备时间
        return $datares;
    }

    //货柜的添加
    public function containeradd($data){
        $ckdata = notEmpty(['name' => lang("container_name"), 'ready_day' => lang("departure_time"), 'number' => lang("container_quantity")]);
        if ($ckdata['status']==2) {
            return $ckdata;
        }
        if (!is_numeric($data['number']) || $data['number']<=0){
            return array('msg'=>lang("quantity_doesn't_meet_the_requirements"),'status'=>0);
        }
        $name='NT'.date('ymd',time()).trim($data['name']);
        $namearr=array();
        //计算加密的密文
        for ($i=1;$i<=$data['number'];$i++){
            if($data['number']==1){
                $rowname=$name;//货柜名称
            }else{
                $rowname=$name.'('.$i.')';//货柜名称
            }
            $row = [
                'name'=>$rowname,//货柜名称
                'ready_day' => strtotime($data['ready_day']),//准备时间
                'type_id' => $data['type_id'],//货柜类型
                'port_start' => $data['port_start'],//出发港
                'port_arrival' => $data['port_arrival'],//到达港
                'co_id_start' => $data['co_id_start'],//出发货贷
                'co_id_arrival' => $data['co_id_arrival'],//到达货贷
                'create_id' => session('userid'),
                'update_id' => session('userid'),
                'create_at' => time(),
                'update_at' => time(),
            ];

            array_push($namearr,$rowname);
            $ids[]=$this->insertGetId($row);
        }
        $rangnum=mt_rand(1,9);
        //批量更新货柜的密文
        foreach ($ids as $idskey=>$idsval){
            $num=substr($idsval,-3);//取后三位数
            $arr=str_split($num, 1);//转换成数组
            $one=$rangnum * $arr[0];
            if ($one<=9){
                $numone = '0'.$one;
            }else{
                $numone=$one;
            }
            if(isset($arr[1])) {
                $two = $rangnum * $arr[1];
                if ($two <= 9) {
                    //含有一位数
                    $numtwo = '0'.$two;
                } else {
                    //含有两位数
                    $numtwo = $two;
                }
            }else{
                $numtwo='00';
            }
            if(isset($arr[2])) {
                $three = $rangnum * $arr[2];
                if ($two <= 9) {
                    //含有一位数
                    $numthree = '0'.$three;
                } else {
                    //含有两位数
                    $numthree = $three;
                }
            }else{
                $numthree='00';
            }
            $code=$numone.$rangnum.$numtwo.$rangnum.$numthree.$rangnum;
            //更新密文
            $updateid=$this->where('id',$idsval)->setField('code',$code);
        }
        $namestr=implode(",", $namearr);
        if ($ids) {
            return array('msg' => $namestr . lang("added_successfully"), 'status' => 1);
        } else {
            return array('msg' => $namestr . lang("add_failed"), 'status' => 0);
        }
    }
    //编辑货柜显示的接口
    public function editinfo($data,$lang){
        $where['a.lang'] = $lang;//语言标志
        $join = [
            ['nt_container_carrier b', 'a.mkey=b.mkey']
        ];
        $table = 'multi_lang';
        $info=getinfo($data['id'],'container');
        $info['update_name']=getinfo($info['update_id'],'admin')['nickname'];//编辑者
        $info['update_date']=getTimeDate($info['update_at'],12);//编辑时间
        $containerwhere['mkey'] = 'container_carrier_' . $info['carrier_id'];
        $info['carrier_id_name'] = getlangname('multi_lang', $containerwhere, $lang);//承运商名称
        //状态
        if ($info['ready_day']>0 && $info['sum_ctn']==0 && !$info['etd_day'] && !$info['eta_day'] && !$info['arrival_day']){
            //准备
            $info['status']='READY';
        }elseif ($info['ready_day']>0 && $info['sum_ctn']>0 && !$info['etd_day'] && !$info['eta_day'] && !$info['arrival_day']){
            //装柜
            $info['status']='LOADING';
        }elseif ($info['etd_day']>0  && !$info['eta_day'] && !$info['arrival_day']){
            //出发
            $info['status']='SALLING';
        }elseif ($info['eta_day']>0 && !$info['arrival_day']){
            //到达
            $info['status']='ARRIVE';
        }elseif ($info['arrival_day']>0){
            //卸货
            $info['status']='DISCHARGE';
        }

        //处理时间
        if ($lang != 'zh') {
            if($info['ready_day']){
                $info['ready_day'] = getTimeDate($info['ready_day'], 13);
            }
            if($info['etd_day']){
                $info['etd_day'] = getTimeDate($info['etd_day'], 13);
            }
            if($info['eta_day']){
                $info['eta_day'] = getTimeDate($info['eta_day'], 13);
            }
        } else {
            if($info['ready_day']){
                $info['ready_day'] = getTimeDate($info['ready_day'], 7);
            }
           if($info['etd_day']){
               $info['etd_day'] = getTimeDate($info['etd_day'], 7);
           }
           if($info['eta_day']){
               $info['eta_day'] = getTimeDate($info['eta_day'], 7);
           }
        }
        $datares=array(
            'container_type'=>getables('container_type',[],'id,name'),//货柜类型
            'port_start'=>getables('port',['country_id'=>2],'id,name'),//出发地
            'port_arrival'=>getables('port',['country_id'=>1],'id,name'), //目标地
            'co_id_start'=>getables('container_agent',['country_id'=>2],'id,name'),// 货贷(中国)
            'co_id_arrival'=>getables('container_agent',['country_id'=>1],'id,name'),  //货贷(巴西)
            'carrier'=>getmultidata($table, $join, $where)['data'],//承运商
            'info'=>$info,
        );
        return $datares;
    }
    public function containeredit($data){
        $ckdata = notEmpty(['name' => lang("container_name"), 'ready_day' => lang("departure_time")]);
        if ($ckdata['status']==2) {
            return $ckdata;
        }
        //处理时间
        $data['ready_day']=strtotime($data['ready_day']);
        if ($data['etd_day']){
            $data['etd_day']=strtotime($data['etd_day']);
        }else{
            $data['etd_day']=null;
        }
        if ($data['eta_day']){
            $data['eta_day']=strtotime($data['eta_day']);
        }else{
            $data['eta_day']=null;
        }
        $data['update_id']=session('userid');
        $data['update_at']=time();
        //对数据的更新的操作
        $updateid=$this->where('id',$data['id'])->update($data);
        if ($updateid!==false){
            return array('msg'=>$data['name'].lang("edited_successfully"),'status'=>1);
        }else{
            return array('msg'=>$data['name'].lang("edit_failed"),'status'=>0);
        }
    }

    //批量调整的显示接口
    public function getchange($data,$lang){
        $map['id']=['in',$data['ids']];
        $datares=getables('container',$map,'id,name,ready_day,etd_day,eta_day,arrival_day');
        foreach ($datares as $datareskey=>$dataresval){
            if ($lang != 'zh') {
                if($dataresval['ready_day']){
                    //准备日期
                    $datares[$datareskey]['ready_day'] = getTimeDate($dataresval['ready_day'], 13);
                }
                if($dataresval['etd_day']){
                    //开航日期
                    $datares[$datareskey]['etd_day'] = getTimeDate($dataresval['etd_day'], 13);
                }
                if($dataresval['eta_day']){
                    //到达日期
                    $datares[$datareskey]['eta_day'] = getTimeDate($dataresval['eta_day'], 13);
                }
                if($dataresval['arrival_day']){
                    //入仓日期
                    $datares[$datareskey]['arrival_day'] = getTimeDate($dataresval['arrival_day'], 13);
                }
            } else {
                if($dataresval['ready_day']){
                    $datares[$datareskey]['ready_day'] = getTimeDate($dataresval['ready_day'], 7);
                }
                if($dataresval['etd_day']){
                    $datares[$datareskey]['etd_day'] = getTimeDate($dataresval['etd_day'], 7);
                }
                if($dataresval['eta_day']){
                    $datares[$datareskey]['eta_day'] = getTimeDate($dataresval['eta_day'], 7);
                }
                if($dataresval['arrival_day']){
                    $datares[$datareskey]['arrival_day'] = getTimeDate($dataresval['arrival_day'], 7);
                }
            }
        }
        $name= implode(',',array_column($datares,'name'));
        $changedata=array('name'=>$name,'data'=>$datares);
        return $changedata;
    }
    //批量调整的提交接口
    public function containerchang($data){
        if (!$data['time']){
            return array('msg'=>lang("please_set_the_time"),'status'=>0);
        }
        $ids=$data['id'];
        $arrname = explode(',',$data['name']);//货柜名称
        if(count($arrname)>3){
            $namecontainer = $arrname[0] . $arrname[1] . $arrname[2] . '...';
        }else{
            $namecontainer= $data['name'];
        }
        $time=strtotime($data['time']);
        $update['update_id']=session('userid');
        $update['update_at']=time();
        if($data['num']==1){
            //准备日期
            $update['ready_day']=$time;
        }elseif ($data['num']==2){
            //开航日期
            $update['etd_day']=$time;
        }elseif ($data['num']==3){
            //到港日期
            $update['eta_day']=$time;
        }elseif ($data['num']==4){
            //入仓日期
            $update['arrival_day']=$time;
        }
        $updateid=$this->where("id in($ids)")->update($update);
        if ($updateid!==false){
            return array('msg'=>$namecontainer.lang("edited_successfully"),'status'=>1);
        }else{
            return array('msg'=>$namecontainer.lang("edit_failed"),'status'=>0);
        }
    }
    //开航 到达 入仓接口
    public function etdetaarrivalday($data){
        $time=$update['update_at']=time();
        $update['update_id']=session('userid');
        $name=trim($data['name']);
        if($data['num']==1){
            $update['etd_day']=$time;
            $yes=$name.lang("sailed_successfully");
            $no=$name.lang("sailing_failed");
        }elseif ($data['num']==11){
            $update['etd_day']=null;
            $yes=$name.lang("cancel_sailed_successfully");
            $no=$name.lang("cancel_sailing_failed");
        }elseif ($data['num']==2){
            $update['eta_day']=$time;
            $yes=$name.lang("successful_arrival");
            $no=$name.lang("arrival_failure");
        }elseif ($data['num']==22){
            $update['eta_day']=null;
            $yes=$name.lang("cancel_successful_arrival");
            $no=$name.lang("cancel_arrival_failure");
        }elseif ($data['num']==3){
            $update['arrival_day']=$time;
            $yes=$name.lang("successfully_entered_the_warehouse");
            $no=$name.lang("failed_to_enter_warehouse");
        }elseif ($data['num']==33){
            $update['arrival_day']=null;
            $yes=$name.lang("cancel_successfully_entered_the_warehouse");
            $no=$name.lang("cancel_failed_to_enter_warehouse");
        }
        $updateid=$this->where('id',$data['id'])->update($update);
        if ($updateid!==false){
            return array('msg'=>$yes,'status'=>1);
        }else{
            return array('msg'=>$no,'status'=>0);
        }
    }
    //货柜删除接口
    public function delcontainer($data){
        $sum_ctninfo=$this->where('id',$data['id'])->find();
        if ($sum_ctninfo['sum_ctn']>0){
            return array('msg' => $data['name'] . lang("contains_total_number_of_boxes_and_can't_be_deleted"), 'status' => 0);
        }
        $buy_poin=Db::name('buy_po_pack')->where('container_id',$data['id'])->find();
        if ($buy_poin){
            return array('msg' => $data['name'] . lang("contains_product_and_can't_be_deleted"), 'status' => 0);
        }
        $retcontainer = $this->where('id', $data['id'])->delete();//货柜表
        if ($retcontainer) {
            return array('msg' => $data['name'] . lang("deleted_successfully"), 'status' => 1);
        } else {
            return array('msg' => $data['name'] . lang("failed_to_delete"), 'status' => 0);
        }
    }
}